package com.pinecone.controller;

import com.pinecone.common.annotation.CurrentUser;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.rong.RongCloud;
import com.pinecone.common.rong.messages.AdminMessage;
import com.pinecone.common.rong.models.ChatRoomInfo;
import com.pinecone.common.rong.models.CodeSuccessResult;
import com.pinecone.common.rong.models.TokenResult;
import com.pinecone.common.utils.R;
import com.pinecone.dto.AdminMsgDto;
import com.pinecone.dto.OttUser;
import com.pinecone.dto.UserDetailsDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * 融云服务控制器
 * Created by hushangjie on 2017/9/21.
 */
@RestController
@RequestMapping("/rong_cloud")
public class RongCloudController extends BaseController{

    @Value("${rongcloud.appkey}")
    private String appkey;
    @Value("${rongcloud.secret}")
    private String secret;

    //管理员后台向聊天室发送活动消息
    //管理员需要提供直播间id,用户id,消息内容
    @PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST')")
    @PostMapping("/send_admin_msg")
    public R sendAdminMessage(@CurrentUser UserDetailsDTO currentUser, @RequestBody @Validated AdminMsgDto adminMsgDto){
        RongCloud rongCloud = RongCloud.getInstance(appkey, secret);
        AdminMessage adminMsg = new AdminMessage(adminMsgDto.getContent());
        String[] tochatRoomIds = {adminMsgDto.getChatRoomId()};
        try {
            rongCloud.message.publishChatroom(currentUser.getId().toString(),tochatRoomIds,adminMsg);
        } catch (Exception e) {
            logger.error("向聊天室发送消息失败");
            throw new MinerException("向聊天室发送消息失败");
        }
        return R.ok();
    }

    /**
     * 聊天室通过qq，微信，微博登录后获取token
     * @param ottUser
     * @return
     */
    @PostMapping("/token")
    public R getRongYunToken(@RequestBody OttUser ottUser) {
        RongCloud rongCloud = RongCloud.getInstance(appkey, secret);
        TokenResult userGetTokenResult = null;
        try {
            userGetTokenResult = rongCloud.user.getToken(ottUser.getOpenId(), ottUser.getNickname(), ottUser.getAvatarUrl());
            if (userGetTokenResult.getCode() == 200){
                return R.ok().put("token",userGetTokenResult.getToken());
            }else {
                return R.error("连接融云服务器异常");
            }
        } catch (Exception e) {
            return R.error("连接融云服务器异常");
        }
    }

    /**
     * 随机token,用于聊天室在线人数计数
     * @return
     */
    @GetMapping("/random_token")
    public R getRandomToken(){
        RongCloud rongCloud = RongCloud.getInstance(appkey, secret);
        String userId = getRandomString(3);
        String username = getRandomString(5);
        TokenResult userGetTokenResult = null;
        try {
            userGetTokenResult = rongCloud.user.getToken(userId, username, "http://www.rongcloud.cn/images/logo.png");
        } catch (Exception e) {
            throw new MinerException("连接融云服务器异常");
        }

        if (userGetTokenResult.getCode() == 200){
            return R.ok().put("token",userGetTokenResult.getToken());
        }else {
            return R.error("连接融云服务器异常");
        }
    }

    /**
     * 服务端创建聊天室
     * @return
     * @throws Exception
     */
    @GetMapping("/create/chat_room")
    public R createChatRoom() throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(appkey, secret);
        String chatroomId = getRandomString(3);
        String chatroomName = getRandomString(3);
        ChatRoomInfo chatRoomInfo = new ChatRoomInfo(chatroomId,chatroomName);
        ChatRoomInfo[] chatRoomInfos = new ChatRoomInfo[1];
        chatRoomInfos[0] = chatRoomInfo;

        CodeSuccessResult codeSuccessResult = rongCloud.chatroom.create(chatRoomInfos);
        return R.ok().put("chatroomId",chatroomId);
    }

    /**
     * 随机数工具
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
